<?php

namespace app\admin\controller\user\party;

use addons\classroom\controller\api\User;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Response;
use think\Db;
use think\Log;
use think\Loader;
use fast\Random;
use fast\Tree;
use app\admin\model\department\Department as DepartmentModel;
use \app\admin\model\department\Admin as DepartmentAdminModel;
// use fast\Closure;

/**
 * 党员信息
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\user\party\Member
     */
    protected $model = null;
    protected $allDepartment = []; //
    protected $childrenGroupIds = []; //权限组
    protected $dadminModel = null; //部门管理员模型
    protected $childrenAdminIds = []; //子管理员ID

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\party\Member;
        $this->view->assign("statusList", $this->model->getStatusList());
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $domain = $_SERVER['HTTP_HOST'];
        $url = $protocol . '://' . $domain;
        $site = config('site');
        $this->view->assign("party_member", $site['party_member']);
        $this->view->assign("url", $url);




        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());

        $this->dadminModel = new DepartmentAdminModel;
        $departmentList = [];
        $this->allDepartment = \app\admin\model\department\Admin::getAllDepartmentsArray($this->auth->id, ($this->auth->isSuperAdmin() || $this->auth->data_scope) ? true : false);
        // echo json_encode($this->allDepartment, JSON_UNESCAPED_UNICODE);
        $this->allDepartment = collection($this->allDepartment)->toArray();

        $departmentdata = [];
        foreach ($this->allDepartment as $k => $v) {
            $state = ['opened' => true];
            $departmentList[] = [
                'id' => $v['id'],
                'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
                'text' => preg_replace('/&nbsp;|\s*|│|└|├\s*/', '', __($v['name'])), //str_replace("&nbsp;",'', __($v['name'])) ,
                'state' => $state
            ];
        }

        $tree = Tree::instance()->init($this->allDepartment, 'parent_id');
        $departmentOptions = $tree->getTree(0, "<option model='@model_id' value=@id @selected @disabled>@spacer@name</option>");

        $this->view->assign('departmentOptions', $departmentOptions);

        $this->assignconfig('departmentList', $departmentList);

        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $admin = model('app\admin\model\department\Admin')->where('admin_id', $this->auth->id)->find();
        foreach ($result as $k => $v) {
            if ($admin) {
                if ($v['id'] != $admin['department_id']) {
                    $departmentdata[$v['id']] = $v['name'];
                }
            } else {
                $departmentdata[$v['id']] = $v['name'];
            }
        }
        // array_shift($departmentdata);
        $this->view->assign('departmentdata', $departmentdata);

        //兼容旧版本没有手机号
        $database = config('database');
        $exits_mobile = \think\Db::query("SELECT 1 FROM  information_schema.COLUMNS WHERE  table_name='{$database['prefix']}admin' AND COLUMN_NAME='mobile' limit 1");
        $this->view->assign('exits_mobile', $exits_mobile ? 1 : 0);
        $this->assignconfig('exits_mobile', $exits_mobile ? 1 : 0);
    }



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $department_id = $this->request->request("department_id");

        if ($this->request->isAjax()) {

            // $this->model = new \app\admin\model\department\AuthAdmin();
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_w = [];

            if (isset($filter['department_id'])) {
                $department_id = $filter['department_id'];
                unset($filter['department_id']);
                $this->request->get(['filter' => json_encode($filter)]);
            }


            if ($department_id) {
                if (!in_array($department_id, array_column($this->allDepartment, 'id'))) {
                    $this->error("您所选的部门没有权限");
                }
                $department_ids = explode(",", $department_id);
                $filter_w['thee_department_id'] = ['in', $department_ids];
            }
            // echo json_encode($filter_w);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'department', 'userinfo'])
                ->where('type', '=', '1')
                ->where($filter_w)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // foreach ($list as $row) {

            //     $row['image'] = empty($row['image']) ? '/assets/addons/classroom/img/noimage.jpg' : $row['image'];
            //     $row->getRelation('category')->visible(['name']);
            // }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function detail($id)
    {
        // // $data = $this->request->request();
        // echo $id;
        $data = $this->model
            ->with(['user', 'department'])
            ->where($this->model->getTable() . '.id', $id)
            ->find();
        $this->view->assign("data", $data);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $edit = $this->model->get($ids);
            $params = $this->request->post("row/a");
            $params['update_time'] = time();
            if ($edit->allowField(true)->save($params)) {
                $this->success(__('修改成功'));
            }
            $this->error(__('操作失败！'));
        }
        $row = $this->model
            ->with(['user', 'department', 'userinfo'])
            ->where($this->model->getTable() . '.id', $ids)
            ->find();
        // echo json_encode($row);
        // die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public function import()
    {
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params || empty($params['import_file_url'])) {
                $this->error('请上传 Excel 文件');
            }

            $filePath = ROOT_PATH . 'public' . $params['import_file_url'];
            if (!file_exists($filePath)) {
                $this->error('文件不存在');
            }

            try {
                $spreadsheet = IOFactory::load($filePath);
                $sheet = $spreadsheet->getActiveSheet();
                $data = $sheet->toArray();

                if (count($data) < 2) {
                    $this->error('Excel 数据为空或格式错误');
                }

                Db::startTrans();

                $insertData = [];
                $userinfoData = [];

                foreach ($data as $key => $row) {
                    if ($key == 0) continue;
                    if (empty($row[5])) continue;

                    $salt = Random::alnum();
                    $password = substr(trim($row[5]), -6);
                    $hashedPassword = md5(md5($password) . $salt);

                    $user = [
                        'username'    => trim($row[7]),
                        'nickname'    => trim($row[0]),
                        'password'    => $hashedPassword,
                        'salt'        => $salt,
                        'mobile'      => trim($row[3]),
                        'email'       => trim($row[4]),
                        'level'       => 1,
                        'gender'      => $row[1] == '男' ? 1 : 0,
                        'name'        => trim($row[0]),
                        'id_no'       => trim($row[5]),
                        'work_number' => trim($row[7]),
                        'is_student'  => $row[6] == '是' ? 1 : 0,
                        'createtime'  => time(),
                    ];
                    $user_info = Db::name('user')->where('username', trim($row[6]))->count();
                    if ($user_info == 0) {
                        $user_id = Db::name('user')->insertGetId($user);
                        if (!$user_id) throw new \Exception("用户 {$row[0]} 插入失败");

                        $partyMember = [
                            'user_id'            => $user_id,
                            'thee_department_id' => $params['area'],
                            'number'             => trim($row[8]),
                            'create_time'        => time(),
                        ];

                        $userinfo = [
                            'user_id'    => $user_id,
                            'name'       => trim($row[0]),
                            'work_number' => trim($row[7]),
                            'level'      => 1,
                        ];

                        $insertData[] = $partyMember;
                        $userinfoData[] = $userinfo;
                    }
                }

                if (!empty($insertData)) {
                    $result = Db::name('user_party_member')->insertAll($insertData);
                    if (!$result) throw new \Exception("user_party_member 插入失败");
                }
                if (!empty($userinfoData)) {
                    $result = Db::name('user_userinfo')->insertAll($userinfoData);
                    if (!$result) throw new \Exception("user_userinfo 插入失败");
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('导入失败：' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine());
                $this->error('导入失败：' . $e->getMessage());
            }
            $this->success('导入成功', '', ['user_party_member' => $insertData, 'user_userinfo' => $userinfoData]);
        }
        return $this->view->fetch();
    }





    /**
     * 下载导入模板
     */
    public function downloadTemplate()
    {
        // 模板文件的路径
        $filePath = ROOT_PATH . 'public/uploads/20250101/0a5ed5afaf38ba115cbe80fbc506bbab.xlsx';
        echo  $filePath;
        // 判断文件是否存在
        if (!file_exists($filePath)) {
            $this->error('模板文件不存在');
        }
        // 设置下载文件的头部信息
        // 获取文件名和 MIME 类型
        // $fileName = basename($filePath);
        // $fileMimeType = mime_content_type($filePath);
        // 设置响应头，手动返回下载
        return \fast\Http::sendToBrowser($filePath, false, true, '党员信息.xlsx');
    }
}
